<?php

class users_controller {
    
    public function exec_index() {
        //Just alias of login
        //May show user profile if already logged in
        return $this->exec_login();
    }
    public function exec_logout(){
        User::logout();
        $content = '<div class="success">You have logged out successfully</div>';
        $data=array('user_name'=>'','remember_me'=>'');
        $content .= $this->show_login_form($data);
        return array('content'=>$content);
    }

    public function exec_passwd(){
        $status = GET_value('s');
        $user_id = SESSION_value('user_id', '');
        $data['user_password'] = strtolower (POST_value('user_password',''));
        $data['new_user_password'] = POST_value('new_user_password','');
        $data['confirm_user_password'] =  POST_value('confirm_user_password',''); 
        if ('submit'==$status){
            $content = 'log thí fucking user in...';  
            $r = User :: passwd($user_id,$data);
            //print_r($r);
            if ($r['success']){
                $content = '<div class="success" style="margin:50px;padding:20px">Đổi mật khẩu thành công!</div>';
                $content .= $this->show_login_form(null);
            }else{
                $content = $this->show_passwd_form($r['error']);
            }
        }else{
            $content = $this->show_passwd_form();
        }
        return array('content'=>$content);        
    }
    
    public function exec_login(){
        $status = GET_value('s');
        $data['user_name'] = strtolower (POST_value('user_name',''));
        $data['user_password'] = POST_value('user_password','');
        $data['remember_me'] =  POST_value('remember_me',''); 
        if ('submit'==$status){
            $content = 'log thí fucking user in...';  
            $r = User :: login($data);
            //print_r($r);
            if ($r['success']){
                $content = '<div class="success">Login successfully!</div>';
                $content .= $this->show_login_form(null);
                header('Location: '.WEBSITE_URL.'/admin/index.php?m=manage_request');
            }else{
                $content = $this->show_login_form($data,$r['error']);
            }
        }else{
            $content = $this->show_login_form($data);
        }
        return array('content'=>$content);
    }
    
    
    private function show_login_form($data,$error=''){
        $tpl = new Template(MODULE_ROOT.'/users/view/login_form.html');
        $tpl -> set('data',$data);
        $tpl -> set('error',$error);
        return $tpl->fetch();
    }
    
    private function show_passwd_form($error=''){
        $tpl = new Template(MODULE_ROOT.'/users/view/passwd_form.html');
        $tpl -> set('error',$error);
        return $tpl->fetch();
    }
    
}